/*
  "name": "大山后台管理系统",
  "version": "1.0",
  "description": "大山中后台管理系统",
  "author": "大山",
  "date": "2023-05-04",
  "license": "MIT",
*/

const bodyParser = require('body-parser');
const jsonParser = bodyParser.json({ limit: '1000mb' });
const resbody = require('../utils/resbody');
const utils = require('../utils/utils');
const token = require('../utils/token');
const connection = require('../utils/sql');
const mysql = require('mysql');
const escape = mysql.escape;
const jwt = require("jsonwebtoken");
const { log } = require('debug/src/node');

module.exports = (app) => {
	// 验证token
	const whiteList = ['/api/login'];
	let userTokenData;
	
	app.use((req,res,next) => {
		if(!whiteList.includes(req.url)) {
			token.verifyToken(req.headers.authorization).then(res => {
				userTokenData = res
				next()
			}).catch(e => {
				// token过期时的err值："message": "jwt expired",
				// token无效时的err值："message": "jwt malformed | invalid token | invalid signature",
				// 没有token的err值："message": "jwt must be provided"
				// console.log(token.tokenMsg(), e.message)
				let msg = token.tokenMsg().find(item => item.type === e.message)['msg'];
				// res.status(200).send(res.json(resbody.getFailResult({}, msg)))
				res.json(resbody.getFailResult({}, msg, 401))
			})
		} else {
			next()
		}
	})
	
	// 字典数据 - 添加数据
	app.post('/api/dictData',(req,res)=>{
	    // 接收参数
	    const { dictLabel, dictType, dictStatus, dictValue, listClass, cssClass, remark } = req.body
	    const id = utils.randomNumber()
	
	    // 判断验证
	    if (!dictLabel) {
			res.json(resbody.getFailResult({}, '请您输入字典数据名称', 0))
	        return false
	    }
		
		if (!dictValue) {
			res.json(resbody.getFailResult({}, '请您输入字典数据值', 0))
			return false
		}
		
		// 值作二次处理，无则下一步
	    const data = {
	        id: id,
	        dictLabel: dictLabel,
	        dictType: dictType,
			dictStatus: dictStatus,
			dictValue: dictValue,
			listClass: listClass,
			cssClass: cssClass,
			createTime: new Date(),
			isDelete: '1'
	    }
	    const sql = 'INSERT INTO dictData SET?';
	    connection(sql, data, (error, result, fileds) => {
	        if(error) {
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        } else {
	            // 返回
	            res.json(resbody.getSuccessResult(result))
				utils.recordOperaLog(connection, `添加[${dictLabel}]字典数据`, userTokenData)
	        }
	    })
	})
	
	// 字典数据 - 分页查询
	app.get('/api/dictDataPages', (req,res) => {
		let sort = 'desc'; // 排序
		const { pageNum, pageSize, dictLabel, dictType, dictStatus } = req.query;

		// 分页
		let num = pageNum ? parseInt(pageNum) - 1 : 0;
		let size = pageSize ? parseInt(pageSize) : 10;
		let skip =  num * size;
		let limit = skip + ',' + size;
		// 模糊查询：姓名和手机号码
		let fuzzyQuery = '';
		let queryArray = [];
		if (dictLabel) {
			let queryVal = `dictLabel like '%${dictLabel}%'`;
			queryArray.push(queryVal);
		}
		if (dictType) {
			let queryVal = `dictType like '%${dictType}%'`;
			queryArray.push(queryVal)
		}
		if (dictStatus) {
			let queryVal = `dictStatus like '%${dictStatus}%'`;
			queryArray.push(queryVal)
		}
		if (queryArray.length === 1) {
			fuzzyQuery = ` where ${queryArray.join(',')} and isDelete<>'0'`
		} else if (queryArray.length === 0) {
			fuzzyQuery = ` where isDelete<>'0'`
		} else {
			fuzzyQuery = ` where ${queryArray.join(',').replace(',', ' and ')} and isDelete<>'0'`
		}
	    const sql = `SELECT id, dictLabel, dictType, dictStatus, dictValue, listClass, cssClass, remark, createTime FROM dictData${fuzzyQuery} order by createTime ${sort} limit ${limit}`;
		const sqlTotal = `SELECT COUNT(id) as total FROM dictData${fuzzyQuery};`;
		
		connection(sql, (error, result, fileds) => {
			console.log(error);
	        if(error) {
	            res.json(resbody.getFailResult(error))
	        }else{
	            // 返回
				result.forEach(item => {
					item.createTime = utils.parseTime(item.createTime)
				})
				utils.getTableTotal(connection, sqlTotal).then(total => {
					const returnNum = num+1;
					const returnData = {
						total: total,
						rows: result,
						pageNum: returnNum,
						pageSize: size
					}
					res.json(resbody.getSuccessResult(returnData))
				}).catch(err => {
					
				})
	        }
	    })
	})
	
	// 字典数据 - 更新数据
	app.put('/api/dictData', (req, res) => {
		const { id, dictLabel, dictType, dictStatus, dictValue, listClass, cssClass, remark } = req.body;
		let submitData = '';
		Object.keys(req.body).forEach((item, index) => {
			if (item !== 'createTime') {
				if (index === Object.keys(req.body).length - 2) {
					submitData += `${item} = '${req.body[item]}'`
				} else {
					submitData += `${item} = '${req.body[item]}',`
				}
			}
		})
	    const sql = `UPDATE dictData SET ${submitData} WHERE id=${escape(id)}`;
	    connection(sql,(error, result, fileds) => {
	        if(error) {
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        }else{
	            res.json(resbody.getSuccessResult(result))
				utils.recordOperaLog(connection, `更新[${dictLabel}]字典数据`, userTokenData)
	        }
	    })
	})
	
	// 字典数据 - 获取单条数据
	app.get('/api/dictData/:id', (req, res, next) => {
		const { id } = req.params
		const sql = `SELECT id, dictLabel, dictType, dictStatus, dictValue, listClass, cssClass, remark, createTime FROM dictData WHERE id=${escape(id)}`
		connection(sql, (error, result, fileds) => {
		    if(error) {
		        console.log(error)
		        res.json(resbody.getFailResult(error))
		    }else{
				// 返回
				if (result.length === 1) {
					result[0].createTime = utils.parseTime(result[0].createTime);
					res.json(resbody.getSuccessResult(result[0]))
				} else {
					res.json(resbody.getSuccessResult({}))
				}
				
		    }
		})
	})
	
	// 字典数据 - 删除单条数据
	app.delete('/api/dictDataDelete/:id', (req, res) => {
		const { id } = req.params
	    const sql = `DELETE FROM dictData WHERE id = '${id}'`;
		// const sql = `UPDATE dictData SET isDelete = '0' WHERE id=${escape(id)}`
	    connection(sql, (error, result, fileds) => {
	        if(error){
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        }else{
	            res.json(resbody.getSuccessResult({}))
				utils.recordOperaLog(connection, `删除字典数据`, userTokenData)
	        }
	    })
	})
	
	// 字典数据 - 删除多条数据
	app.delete('/api/dictDataMultipleDelete', (req, res) => {
		const { ids } = req.query;
		let deleteIdsArray = ids.split(',');
		let deleteIds = [];
		deleteIdsArray.forEach(item => {
			deleteIds.push(`'${item}'`)
		})
		deleteIds = deleteIds.join(',');
	    const sql = `DELETE FROM dictData WHERE id in (${deleteIds})`;
		// const sql = `UPDATE dictData SET isDelete = '0' WHERE id in (${deleteIds})`
	    connection(sql, [], (error, result, fileds) => {
	        if(error){
	            console.log(error)
	            res.json(resbody.getFailResult(error))
	        }else{
	            res.json(resbody.getSuccessResult({}))
				utils.recordOperaLog(connection, `删除多条字典数据`, userTokenData)
	        }
	    })
	})
}
